import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Textarea, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      faces: []
    }
    this.types = {
      '0': '本人',
      '1': '访客',
      '2': '家人',
      '3': '租客',
    }
    this.loading = false;
    this.loadFaces.bind(this);
    Event.on('updateFaces', async () => {
      this.loading = false;
      await this.loadFaces();
    })
  }

  componentWillMount () {
    Taro.setNavigationBarTitle({
      title: global.isGuest ? '我的访客' : '门禁管理'
    });
    this.loadFaces();
  }

  componentDidMount () {}

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  async loadFaces() {
    if (this.loading) {
      return;
    }
    await Taro.showLoading({
      title: '加载中...'
    });
    this.loading = true;
    try {
      let res = await Request.get(`/business/face/list?userId=${global.userInfo.userId}&villageId=${global.currentBindingVillage.villageId}`);
      if (res.data.code !== 200) {
        throw new Error();
      }
      this.setState({
        faces: res.data.rows
      })
    } catch (e) {
      console.log('加载门禁数据失败')
    } finally {
      await Taro.hideLoading();
      this.loading = false;
    }
  }

  render() {
    let {faces} = this.state;
    return <View className='face_list'>
      <View className='face_container'>
        {
          faces.length > 0 ?
            faces.map(item => (<View className='face_item'>
              <Image src={Request.imgHost + item.resource}/>
              <View className='tips'>
                <View>
                  <Text>{item.name}</Text>
                  <Text>({this.types[item.type]})</Text>
                </View>
                <View>
                  <Text>{item.status === '1' ? '待审核' : item.status === '2' ? '审核通过' : '未通过'}</Text>
                </View>
              </View>
            </View>))
            :
            global.isGuest ?
              <View className='message_container'>
                暂未有访客门禁，<Text onClick={() => Taro.navigateTo({url: '/pages/face_detail/index'})}>点击新增访客门禁</Text>
              </View>
              :
              <View className='message_container'>
                暂未有门禁图片，<Text onClick={() => Taro.navigateTo({url: '/pages/face_detail/index'})}>点击新增门禁</Text>
              </View>
        }
      </View>
      {
        faces.length !== 0 && <View className='cars_item add_btn' onClick={() => Taro.navigateTo({url: '/pages/face_detail/index'})}>
          <Text className='iconfont icon-add size50 color-grey'/>
        </View>
      }
    </View>
  }
}
